﻿

CREATE proc [accounting].[SaveAccount2Company]
@AccountID		int,
@OrgKey			int
as
begin
	set nocount on

	declare @rc int,
			@logText nvarchar(150)

	

	begin tran

	begin try
		if @OrgKey > 0
		begin
			;with sel
			as
			(
				select	@AccountID		'AccountID',
						@OrgKey			'OrgKey'
			)
			merge into [accounting].[mnAccount2Company] t
			using sel s on
				s.AccountID = t.AccountID
					and s.OrgKey = t.OrgKey
			when not matched then
			insert (
					AccountID, 
					OrgKey
					)
			values (
					s.AccountID, 
					s.OrgKey
					)
			;
		end 

		if @OrgKey = -1 --Ef
		begin
			update accounting.AccountsStructure
			set		Ef = 1
			where AccountID = @AccountID
		end

		if @OrgKey = -2 --Og
		begin
			update accounting.AccountsStructure
			set		Og = 1
			where AccountID = @AccountID
		end

	end try
	begin catch
		select @AccountID 'AccountID', 0 'Return', ERROR_MESSAGE() 'Error'
		goto WithError
	end catch

	select @AccountID 'AccountID', 0 'Return', null 'Error'

	commit tran
	
	return 0

WithError:
	if @@TRANCOUNT > 0
	begin
		set @logText = 'AccountID: ' + cast(@AccountID as char(10)) + ' OrgKey: ' + cast(@OrgKey as char(10))
		exec @rc = dbo.SaveLog
			@UserID = 999, --Agent
			@LogType = 'S',
			@LogArea = 'Ac',
			@LogDetails = @logText,
			@IsError = 1
		rollback tran
	end
	return -1
end
GO


